package com.behome.netty.netty_A.bean;



import com.behome.netty.common.ByteConventerKit;

import java.nio.ByteBuffer;

/**
 * Created by cky on 2020/6/11.
 *
 */
public abstract class ProtocolAPacketBase extends PacketBase {
    protected short headVersion = 1;//版本号
    protected static final int MIN_LENGTH = 15;
    protected static final int HEAD_LENGTH = 9;
    protected static final int TAIL_MIN_LENGTH = 6;
    protected static final int INDEX_BODY_LENGTH = 5;
    protected static final int INDEX_HEAD_VERSION = 1;
    protected static final int INDEX_PROTOCOL_TYPE = 3;

    protected ProtocolAPacketBase(byte[] data) {
        super(data);
    }

    public short getRequestId() {
        return this.headVersion;
    }

    public void setRequestId(short id) {
        this.headVersion = id;
    }

    protected byte[] serializeHead(int bodyLength) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(HEAD_LENGTH);
//        byte[] bytes = ByteConventerKit.shortToBytes(this.headVersion);
//        byte cmdTypeValue = this.getCmdTypeValue();//04  通用紧急/日常广播开关机指令；
//        byte cmdSourceValue = this.getCmdSourceValue();//01 表示消息来自平台软件
//        byte[] bytes1 = ByteConventerKit.intToBytes2(bodyLength);//指令数据长度
        byteBuffer.put(this.getCmdHeadFlag()).put(ByteConventerKit.shortToBytes(this.headVersion)).put(this.getCmdTypeValue()).put(this.getCmdSourceValue()).put(ByteConventerKit.intToBytes2(bodyLength));
        return byteBuffer.array();
    }

    public byte[] serialize() {
        byte[] bodyBytes = this.serializeBody();
        byte[] headBytes = this.serializeHead(bodyBytes.length);
        byte[] headBodyData = new byte[headBytes.length + bodyBytes.length];
        System.arraycopy(headBytes, 0, headBodyData, 0, headBytes.length);
        System.arraycopy(bodyBytes, 0, headBodyData, headBytes.length, bodyBytes.length);
        byte[] signData = this.getSignData(headBodyData);
        int allLength = headBytes.length + bodyBytes.length + TAIL_MIN_LENGTH + signData.length;
        ByteBuffer byteBuffer = ByteBuffer.allocate(allLength);
        byteBuffer.put(headBytes).put(bodyBytes).put(ByteConventerKit.shortToBytes((new Integer(signData.length)).shortValue())).put(signData);
        int pos = byteBuffer.position();
        byte[] tmpData = new byte[byteBuffer.position()];
        byteBuffer.position(0);
        byteBuffer.get(tmpData, 0, tmpData.length);
        byteBuffer.position(pos);
        byte[] crc32Data = this.getCRC32Bytes(tmpData);
        byteBuffer.put(crc32Data);
        byte[] array = byteBuffer.array();
        return byteBuffer.array();
    }

    public abstract byte getCmdHeadFlag();

    public abstract byte getCmdSourceValue();

    public abstract byte getCmdTypeValue();

    public abstract String getCmdType();

    public abstract String getCmdTypeName();

    protected abstract byte[] serializeBody();

    protected abstract void deserializeBody(byte[] var1);
}
